/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.passbookviet.pass;

import com.ryantenney.passkit4j.Pass;
import com.ryantenney.passkit4j.PassResource;
import com.ryantenney.passkit4j.PassSerializer;
import com.ryantenney.passkit4j.model.Barcode;
import com.ryantenney.passkit4j.model.BarcodeFormat;
import com.ryantenney.passkit4j.model.Color;
import com.ryantenney.passkit4j.model.Location;
import com.ryantenney.passkit4j.model.NumberField;
import com.ryantenney.passkit4j.model.StoreCard;
import com.ryantenney.passkit4j.model.TextField;
import com.ryantenney.passkit4j.sign.PassSigner;
import com.ryantenney.passkit4j.sign.PassSignerImpl;
import com.ryantenney.passkit4j.sign.PassSignerImpl.Builder;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.security.KeyPair;
import java.security.Security;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import org.bouncycastle.openssl.PEMReader;
import org.bouncycastle.openssl.PasswordFinder;

/**
 *
 * @author Bach
 */
public class MainTest {

    public static void main(String[] args) throws Throwable {
        File f = new File(".");
        System.out.println(f.getAbsolutePath());
        File fResourceFolder = new File("./src/java/vn/passbookviet/resources/");
        if (!fResourceFolder.exists()) {
            System.out.println("Folder Resource not exist !");
            return;
        }
        File fStoreCardFolder = new File(fResourceFolder, "storecard");
        File fCerFolder = new File(fResourceFolder, "certificate");

        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        Pass pass = new Pass()
                .teamIdentifier("team-identifier")
                .passTypeIdentifier("pass.com.bouldercoffeeco.storeCard")
                .organizationName("Boulder Coffee Co.")
                .description("Boulder Coffee Rewards Card Example")
                .serialNumber("p69f2J")
                .webServiceURL("https://example.com/passes/")
                .authenticationToken("vxwxd7J8AlNNFPS8k0a0FfUFtq0ewzFdc")
                .locations(new Location(37.6189722, -122.3748889))
                .barcode(new Barcode(BarcodeFormat.PDF417, "12345678"))
                .logoText("Boulder Coffee Co.")
                .foregroundColor(Color.WHITE)
                .backgroundColor(new Color(118, 74, 50))
                .passInformation(
                new StoreCard()
                .primaryFields(
                new NumberField("balance", "remaining balance", 25)
                .currencyCode("USD"))
                .auxiliaryFields(
                new TextField("level", "LEVEL", "Gold"),
                new TextField("usual", "THE USUAL", "Iced Mocha"))
                .backFields(
                new TextField("terms", "TERMS AND CONDITIONS",
                "Generico offers this pass, including all information, software, products and services available from this pass or offered as part of or in conjunction with this pass (the \"pass\"), to you, the user, conditioned upon your acceptance of all of the terms, conditions, policies and notices stated here. Generico reserves the right to make changes to these Terms and Conditions immediately by posting the changed Terms and Conditions in this location.\n\nUse the pass at your own risk. This pass is provided to you \"as is,\" without warranty of any kind either express or implied. Neither Generico nor its employees, agents, third-party information providers, merchants, licensors or the like warrant that the pass or its operation will be accurate, reliable, uninterrupted or error-free. No agent or representative has the authority to create any warranty regarding the pass on behalf of Generico. Generico reserves the right to change or discontinue at any time any aspect or feature of the pass.")));
        {
            File[] arrFileRes = fStoreCardFolder.listFiles();
            PassResource[] arrRes = new PassResource[arrFileRes.length];
            for (int i = 0; i < arrFileRes.length; i++) {
                arrRes[i] = new PassResource(arrFileRes[i].getName(), arrFileRes[i]);
            }
            pass.files(arrRes);
        }

        Builder builder = PassSignerImpl.builder();
        builder.intermediateCertificate(new FileInputStream(new File(fCerFolder, "AppleWWDRCA.cer")));

        {
            File fPrivateKeyFile = new File(fCerFolder, "exported-key");
            BufferedReader br = new BufferedReader(new FileReader(fPrivateKeyFile));
            KeyPair kp = (KeyPair) new PEMReader(br, new PasswordFinder() {
                @Override
                public char[] getPassword() {
                    return "1234".toCharArray();
                }
            }).readObject();
            builder.privateKey(kp.getPrivate());
        }
        {
            File fSigningCertificate = new File(fCerFolder, "exported-cer");
            CertificateFactory factory = CertificateFactory.getInstance("X.509");
            X509Certificate certificate = (X509Certificate) factory.generateCertificate(new FileInputStream(fSigningCertificate));
            builder.signingCertificate(certificate);
        }

//        builder.keystore(new FileInputStream(
//                new File(fCerFolder, "Certificates.p12")), "1234");

        PassSigner signer = builder.build();
        File fO = new File("D:\\StoreCard.pkpass");
        try {
            PassSerializer.writePkPassArchive(pass, signer, new FileOutputStream(fO));
        } catch (IOException ex) {
            ex.printStackTrace();
            System.out.println("--------------------------------------------------");
        }

        System.out.println("Output at: " + fO.getAbsolutePath());
    }
}
